package com.itheima.googleplay9.ui.fragment;

import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.itheima.googleplay9.R;
import com.itheima.googleplay9.adapter.HomeAdapter;
import com.itheima.googleplay9.adapter.SubjectAdapter;
import com.itheima.googleplay9.api.DataLoader;
import com.itheima.googleplay9.api.Url;
import com.itheima.googleplay9.bean.Subject;
import com.itheima.googleplay9.util.LogUtil;
import com.itheima.googleplay9.util.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lxj on 2016/5/23.
 */
public class SubjectFragment extends BaseFragment implements PullToRefreshBase.OnRefreshListener{
    private PullToRefreshListView refreshListView;
    private ListView listView;
    private SubjectAdapter subjectAdapter;
    private ArrayList<Subject> list = new ArrayList<>();
    @Override
    protected View getSuccessView() {
        refreshListView = (PullToRefreshListView) View.inflate(getActivity(), R.layout.ptr_listview,null);
        //2.设置刷新模式，
        refreshListView.setMode(PullToRefreshBase.Mode.BOTH);//上拉和下拉都有
        //3.设置刷新监听器
        refreshListView.setOnRefreshListener(this);
        //4.获取其中包裹的listview，
        listView = refreshListView.getRefreshableView();
        //去掉listview默认的状态选择器
        listView.setSelector(android.R.color.transparent);
        //去掉listview的默认的分割线
        listView.setDivider(null);

        //给listview设置adapter
        subjectAdapter = new SubjectAdapter(list);
        listView.setAdapter(subjectAdapter);

        return refreshListView;
    }

    @Override
    protected Object onLoad() {
        //如果是下拉刷新，则清空集合
        if(refreshListView.getCurrentMode()== PullToRefreshBase.Mode.PULL_FROM_START){
            list.clear();
        }

        final ArrayList<Subject> subjects = (ArrayList<Subject>) DataLoader.getInstance().loadListData(Url.Subject+list.size()
                ,new TypeToken<List<Subject>>(){}.getType());
            if(subjects!=null){
                list.addAll(subjects);
                Utils.runOnUIThread(new Runnable() {
                    @Override
                    public void run() {
//                        LogUtil.e(this,"subjects 大小： "+subjects.size());
                        //更新adapter
                        subjectAdapter.notifyDataSetChanged();

                        //完成刷新状态
                        refreshListView.onRefreshComplete();
                    }
                });
        }

        return list;

    }

    @Override
    public void onRefresh(PullToRefreshBase refreshView) {
        loadingPage.loadData();
    }
}
